package com.lcxw.hxzbapi.controller.membercontroller;

/**
 * 头像管理controller
 *
 * @author lcxw
 */

import com.alibaba.fastjson.JSONObject;
import com.lcxw.hxzbapi.entity.pojo.Photo;
import com.lcxw.hxzbapi.service.PhotoService;
import com.lcxw.hxzbapi.tencentim.common.TencentImRealization;
import com.lcxw.hxzbcommon.entity.ErrorCode;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.lcxw.hxzbapi.entity.pojo.YwpdMember;
import com.lcxw.hxzbapi.entity.response.Response;
import com.lcxw.hxzbapi.service.YwpdMemberService;
import com.lcxw.hxzbcommon.common.ObsUtil;
import com.lcxw.hxzbcommon.common.StringUtil;

/**
 * @author lcwx
 */
@RestController
@RequestMapping("/api/user")
@CrossOrigin
@Validated
public class ImgPicController {

    private Logger logger = LoggerFactory.getLogger(ImgPicController.class);

    private ObsUtil obsUtil = new ObsUtil();

    @Resource
    YwpdMemberService ywpdMemberService;

    @Resource
    TencentImRealization tencentImRealization;

    @Resource
    PhotoService photoService;

    @PostMapping("/setimg")
    public Response setimg(@Valid @RequestBody JSONObject requestParams) {

        if (StringUtil.isEmpty(requestParams.getString("img"))) {
            logger.error("{} set img failed,because img info is null",
                requestParams.getString("userId"));
            return Response.wrongParam(logger, "img");
        }

        String imgOrigin = requestParams.getString("img");

        String userId = requestParams.getString("userId");
        String imgName = "img/" + userId + "_img.png";

        String imgUrl;
        try {
            imgUrl = obsUtil.uploadPic(imgName, imgOrigin);
        } catch (Exception e) {
            return Response
                .common(logger, "上传用户头像失败", ErrorCode.EXTERNAL_ERROR, "upload img", null);
        }

        logger.info("{} imgurl is generated:{}", userId, imgUrl);

        //将生成的图片URL插入到数据库
        YwpdMember ywpdmember;
        try {
            ywpdmember = ywpdMemberService.selectYwpdMemberByUserId(Long.parseLong(userId));
            ywpdmember.setImgUrl(imgUrl);
            ywpdMemberService.updateYwpdMember(ywpdmember);

            Photo photo = new Photo();
            photo.setUserId(Long.valueOf(userId));
            photo.setPhotoName(userId + "-1");
            photo.setPhotoUrl(imgUrl);
            photoService.insert(photo);
        } catch (Exception e) {
            return Response.dbFail(logger, "db operate");
        }

        //将用户头像地址更新到腾讯IM系统中
        JSONObject imBody = new JSONObject();
        imBody.put("From_Account", userId + "");
        List<JSONObject> profileItem = new ArrayList<>();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("Tag", "Tag_Profile_IM_Image");
        jsonObject.put("Value", imgUrl);
        profileItem.add(jsonObject);
        imBody.put("ProfileItem", profileItem);
        tencentImRealization.updateImUserInfo(imBody);

        Map<String, String> data = new LinkedHashMap<>();
        data.put("imgurl", imgUrl);
        return Response.ok(data);
    }

    @PostMapping("/getimg")
    public Response getUserImgUrl(@RequestBody JSONObject requestParams) {
        logger.info("user {} want to get user {}'s imgurl.", requestParams.getString("userId"),
            requestParams.getString("imgUserId"));
        if (StringUtil.isEmpty(requestParams.getString("imgUserId"))) {
            return Response.wrongParam(logger, "imgUserId");
        }
        Response response = new Response();
        long imgUserId = Long.parseLong(requestParams.getString("imgUserId"));

        try {
            String imgUrl = ywpdMemberService.selectImgUrlByuserId(imgUserId);
            response.setDesc("get user imgUrl success");
            Map<String, String> data = new LinkedHashMap<>();
            data.put("imgUrl", imgUrl);
            response.setData(data);
        } catch (Exception e) {
            e.printStackTrace();
            return Response.dbFail(logger, "get user {" + imgUserId + "}'s imgUrl");
        }

        return response;
    }

}
